// src/store/useCounterStore.js
import {
	defineStore
} from 'pinia'
import {
	reactive,
	ref
} from 'vue'
import {
	getUserInfoAPI
} from '../apis'

export const useUserStore = defineStore('userStore', () => {
	let userInfo = reactive({})
	const setUserInfo = async () => {
		const userId = uni.getStorageSync('userId')
		const {
			data: res
		} = await getUserInfoAPI(userId)
		Object.assign(userInfo, res)
	}
	const clearUserInfo = () => {
		Object.keys(userInfo).forEach(key => {
			delete userInfo[key];
		});
	}
	// 记录还未提交订单选择的乘车人
	let orderRider = ref([])
	const addOrderRider = (rider) => {
		const result = orderRider.value.find(item => item.id === rider.id)
		if (result) {
			return uni.showToast({
				title: '该乘车人已经存在',
				icon: "none"
			})
		}
		orderRider.value.push(rider)
	}
	const clearOrderRider = () => {
		orderRider.value = []
	}

	// 存储始发地和目的地
	let address = ref({
		startingLocation: "",
		destination: ""
	})
	const storeStartingLocation = (item) => {
		address.value.startingLocation = item.address
	}
	const storeDestination = (item) => {
		address.value.destination = item.address
	}
	return {
		userInfo,
		setUserInfo,
		clearUserInfo,
		orderRider,
		addOrderRider,
		clearOrderRider,
		address,
		storeStartingLocation,
		storeDestination
	}
}, {
	persist: {
		storage: {
			setItem(key, value) {
				uni.setStorageSync(key, value)
			},
			getItem(key) {
				return uni.getStorageSync(key)
			},
		},
	}
})